package system_smtp_service

import (
	"math/rand"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/configuration"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/dao"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/service"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/service/system_smtp_service/provider"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/service/system_smtp_service/provider/smtp"
)

func New(smtpLog dao.SystemSmtpLog, smtpLogAttachment dao.SystemSmtpLogAttachment) *Smtp {
	return &Smtp{
		BaseService:       service.New(smtpLog),
		smtpLog:           smtpLog,
		smtpLogAttachment: smtpLogAttachment,
	}
}

type Smtp struct {
	*service.BaseService

	smtpLog           dao.SystemSmtpLog
	smtpLogAttachment dao.SystemSmtpLogAttachment
}

func (cls *Smtp) GetProvider() (provider.Provider, errors.Error) {
	switch configuration.Configuration.Smtp.ProviderPolicy {
	case "first":
		for _, provider := range configuration.Configuration.Smtp.Providers {
			if provider.Enable {
				switch provider.Type {
				case "smtp":
					return smtp.New(provider)
				}

				return nil, errors.ErrorServerInternalError("ISS_TP.S_TP.GP_ER.362540", "无效的SMTP提供商类型[%s]", provider.Type)
			}
		}

		return nil, errors.ErrorServerInternalError("ISS_TP.S_TP.GP_ER.362323", "没有活动的SMTP提供商")
	case "random":
		var providers = make([]configuration.SmtpProvider, 0)
		for _, provider := range configuration.Configuration.Smtp.Providers {
			if provider.Enable {
				providers = append(providers, provider)
			}
		}

		if len(providers) == 0 {
			return nil, errors.ErrorServerInternalError("ISS_TP.S_TP.GP_ER.", "没有活动的SMTP提供商")
		}

		var index = rand.Intn(len(providers))
		var provider = providers[index]

		switch provider.Type {
		case "smtp":
			return smtp.New(provider)
		}

		return nil, errors.ErrorServerInternalError("ISS_TP.S_TP.GP_ER.592516", "无效的SMTP提供商类型[%s]", provider.Type)
	}

	return nil, errors.ErrorServerInternalError("ISS_TP.S_TP.GP_ER.292120", "无效的SMTP选择协议[%s]", configuration.Configuration.Smtp.ProviderPolicy)
}
